import 'dart:io';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart' as compress;
import 'package:largefriends/net/lf_api_url.dart';
import 'package:largefriends/net/lf_dio_util.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../entity/entities/lf_photo_entity.dart';

Future<List<LfPhotoEntity>> uploadFile({
  required List<AssetEntity> fileList,
  bool needCompress = true,
  ProgressCallback? onSendProgress,
}) async {
  var results = await _uploadAction(fileList, apiUrl: apiUploadFile);
  return results;
}

///登录后更新头像使用的
Future<List<LfPhotoEntity>> uploadPicture({
  required List<AssetEntity> fileList,
  bool needCompress = true,
  ProgressCallback? onSendProgress,
  int type = 1,

  ///1 public 2:private
}) async {
  var results =
      await _uploadAction(fileList, apiUrl: apiUploadPhoto, type: type);
  return results;
}

Future<List<LfPhotoEntity>> _uploadAction(
  List<AssetEntity> fileList, {
  required String apiUrl,
  bool needCompress = true,
  int type = 0,
}) async {
  var formData = FormData();
  List<LfPhotoEntity> resultList = List.empty(growable: true);
  for (var i = 0; i < fileList.length; i++) {
    File? file = await fileList[i].file;
    if (file == null) {
      continue;
    }
    if (needCompress) {
      Uint8List? compressed = await compressPhoto(file);
      if (compressed?.isNotEmpty ?? false) {
        formData.files.add(MapEntry(
            'file',
            MultipartFile.fromBytes(compressed!,
                filename: DateTime.now().microsecondsSinceEpoch.toString())));
      }
    } else {
      formData.files.add(MapEntry(
          'file',
          await MultipartFile.fromFile(file.path,
              filename: DateTime.now().microsecondsSinceEpoch.toString())));
    }
  }
  if (apiUrl == apiUploadPhoto && type > 0) {
    ///登录成功后上传相册时使用
    formData.fields.add(MapEntry('photoType', type.toString()));
  }
  await LfDio()
      .post<List<LfPhotoEntity>>(
    url: apiUrl,
    params: formData,
    // onSendProgress: onSendProgress,
  )
      .then((value) {
    resultList.addAll(value);
  }, onError: (error) {
    throw error;
  });

  return resultList;
}

Future<Uint8List?> compressPhoto(File file) async {
  var result = await compress.FlutterImageCompress.compressWithFile(
    file.path,
    minWidth: 1080,
    minHeight: 1920,
  );
  return result;
}
